import { currentInstance, setCurrentInstance } from "./component.js";

export let LicycleHooks;
(function (LicycleHooks) {
  LicycleHooks["BEFORE_MOUNT"] = "bm";
  LicycleHooks["MOUNTED"] = "m";
  LicycleHooks["BFORE_UPDATE"] = "bu";
  LicycleHooks["UPDATED"] = "u";
  LicycleHooks["BEFORE_UNMOUNT"] = "bum";
  LicycleHooks["UNMOUNTED"] = "um";
})(LicycleHooks || (LicycleHooks = {}));

// 发布“订阅”
function createHook(type) {
  // hook 是用户传递的函数
  return (hook, target = currentInstance) => {
    // 通过闭包缓存变量
    if (target) {
      const hooks = target[type] || (target[type] = []);
      const wrapper = () => {
        // 事件订阅保存执行信息
        setCurrentInstance(target);
        hook();
        setCurrentInstance(null);
      };
      hooks.push(wrapper);
    }
  };
}

export const onBeforeMount = createHook(LicycleHooks.BEFORE_MOUNT);
export const onMounted = createHook(LicycleHooks.MOUNTED);
export const onBeforeUpdate = createHook(LicycleHooks.BFORE_UPDATE);
export const onUpdated = createHook(LicycleHooks.UPDATED);
export const onBeforeUnmount = createHook(LicycleHooks.BEFORE_UNMOUNT);
export const onUnmounted = createHook(LicycleHooks.UNMOUNTED);
